﻿# -*- coding:utf-8 -*-

import sys
import urllib 
import urllib2 
import cookielib 
import hashlib
import logging
from time import time
import json

class MessageCode(object):
    #"""网易云信 短信模板：
    #• 短信由三部分构成：签名+内容+变量

    def __init__(self):
        super(MessageCode, self).__init__()
        sys.stdout.flush() 
        self.cookie = cookielib.CookieJar() 
        self.handler = urllib2.HTTPCookieProcessor(self.cookie) 
        self.opener = urllib2.build_opener(self.handler) 
        urllib2.install_opener(self.opener)

    def addHeaders(self, name, value): 
        self.opener.addheaders.append((name, value))

    def doPost(self, url, payload = None): 
        req = urllib2.Request(url, data = payload) 
        req = self.opener.open(req) 
        return req

    def checkSum(self,appSecret,nonce,curTime):
        # SHA1(AppSecret + Nonce + CurTime),三个参数拼接的字符串，
        # 进行SHA1哈希计算，转化成16进制字符(String，小写)
        return hashlib.sha1(appSecret + nonce + curTime).hexdigest()

    def send(self, mobile_phone):
        appSecret = 'afd9fda65a37'
        nonce = '123456' #随机数（最大长度128个字符）
        curTime = str(int(time()))
        self.addHeaders('AppKey', 'd169ab7a832af4750f8cc87875d41dfb')
        self.addHeaders('CheckSum', self.checkSum(appSecret,nonce,curTime))
        self.addHeaders('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8')
        self.addHeaders('CurTime', curTime)
        self.addHeaders('Nonce', nonce)

        templateid = '3049170'
        mobile = mobile_phone
        codeLen = 6    # 设置验证码的长度
        values = {'templateid' : templateid, 'mobile' : mobile, 'codeLen': codeLen}
        postData = urllib.urlencode(values) 

        postUrl = 'https://api.netease.im/sms/sendcode.action'

        try: 
            req = self.doPost(postUrl, postData) 
            if 200 == req.getcode(): 
                res = req.read()
                jsonData = json.loads(res)
                # print jsonData['code']
                return jsonData

                #成功返回{"code":200,"msg":"sendid","obj":8}
                #主要的返回码200、315、403、413、414、500
                #详情：http://dev.netease.im/docs?doc=server&#code状态表
            else: 
                print req.getcode()
                return {'code':0}
        except Exception, e: 
            print logging.exception(e)
            return {'code':-1}

    def verifyCode(self, mobile_phone, code):
        appSecret = 'afd9fda65a37'
        nonce = '123456'  # 随机数（最大长度128个字符）
        curTime = str(int(time()))

        self.addHeaders('AppKey', 'd169ab7a832af4750f8cc87875d41dfb')
        self.addHeaders('CheckSum', self.checkSum(appSecret, nonce, curTime))
        self.addHeaders('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8')
        self.addHeaders('CurTime', curTime)
        self.addHeaders('Nonce', nonce)

        mobile = mobile_phone

        values = {'mobile': mobile, 'code': code}
        postData = urllib.urlencode(values)

        postUrl = 'https://api.netease.im/sms/verifycode.action'

        try:
            req = self.doPost(postUrl, postData)
            if 200 == req.getcode():
                res = req.read()
                jsonData = json.loads(res)
                # print jsonData['code']
                return jsonData

                # 成功返回{"code":200,"msg":"sendid","obj":8}
                # 主要的返回码200、315、403、413、414、500
                # 详情：http://dev.netease.im/docs?doc=server&#code状态表
            else:
                print req.getcode()
                return {'code': 0}
        except Exception, e:
            print logging.exception(e)
            return {'code': -1}

if __name__ == '__main__':
    sendTest = MessageCode()
    # sendTest.send('15680829524')

    # sendTest.verifyCode('15680829524','466161')